package logic

import (
	"context"
	"encoding/hex"

	"greet/internal/svc"
	"greet/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"golang.org/x/crypto/chacha20"
)

type EncryptLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewEncryptLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EncryptLogic {
	return &EncryptLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *EncryptLogic) Encrypt(req *types.EncryptRequest) (resp *types.EncryptResponse, err error) {
	key, err := hex.DecodeString(req.Key)
	if err != nil || len(key) != chacha20.KeySize {
		return &types.EncryptResponse{
			Code:    "error",
			Message: "Invalid key size or format",
		}, nil
	}

	nonce, err := hex.DecodeString(req.Nonce)
	if err != nil || len(nonce) != chacha20.NonceSize {
		return &types.EncryptResponse{
			Code:    "error",
			Message: "Invalid nonce size or format",
		}, nil
	}

	cipher, err := chacha20.NewUnauthenticatedCipher(key, nonce)
	if err != nil {
		return &types.EncryptResponse{
			Code:    "error",
			Message: "Failed to create cipher",
		}, nil
	}

	plaintext := []byte(req.Plaintext)
	ciphertext := make([]byte, len(plaintext))
	cipher.XORKeyStream(ciphertext, plaintext)

	return &types.EncryptResponse{
		Code:    "success",
		Message: "Encrypted using ChaCha20",
		Data: map[string]string{
			"ciphertext": hex.EncodeToString(ciphertext),
		},
	}, nil
}
